package com.jlju.djmhadmin.controller;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.jlju.djmhadmin.common.GenericResponse;
import com.jlju.djmhadmin.common.util.*;
import com.jlju.djmhadmin.dao.entity.Teacher;
import com.jlju.djmhadmin.dao.service.TeacherService;
import com.jlju.djmhadmin.dao.service.UserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpSession;
import java.util.List;
import java.util.concurrent.Callable;

/**
 * All rights Reserved, Designed By Liting.
 *
 * @description: 教师信息相关controller
 * @author: LiTing[liting08011@163.com]
 * @create: 2018-04-19 17:51
 * @Copyright ©2018 Liting. All rights reserved.
 * 注意：本内容仅限于吉林建筑大学ACM协会内部传阅，禁止外泄以及用于其他的商业用途。
 **/
@Slf4j
@RestController
@RequestMapping("/teacher")
@Api("教师相关信息操作")
public class TeacherController {

    private Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    private TeacherService teacherService;

    @Autowired
    private UserService userService;

    @ApiOperation("注销")
    @RequestMapping(value = "/delete")
    @RequiredStringValidator(fieldName="acNo",trim=true,errCode="ACM9900",errMsg="请求参数不足,学号不能为空")
    public Callable<GenericResponse<String>> delete(@RequestBody String json, HttpSession session) {
        logger.info("***教师档案注销开始***入参：" + json);
        try {
            if("2".equals(session.getAttribute("type"))){
                throw new Exception("对不起，您无操作权限");
            }
            json = StringUtils.trimFirstAndLastChar(json,'\"');
            Teacher teacher = new Teacher(json);
            this.teacherService.deleteById(teacher);
            logger.info("***教师档案注销成功***");
//            this.teacherService.postMail(teacher.getEmail(), "学籍注销成功， 学号： " + teacher.getAcNo() + "姓名 ：" + teacher.getName());
            return () -> GenericResponse.success("ACM0701", "教师档案注销成功", teacher);
        } catch (Exception e) {
            logger.info("***教师档案注销失败***" + e);
            return () -> GenericResponse.failed("ACM0702", "教师档案注销失败");
        }
    }


    @ApiOperation("新增教师信息")
    @Validations(requiredStrings={
            @RequiredStringValidator(fieldName="name",errCode="ACM0204",errMsg="请求参数不足,姓名不能为空"),
            @RequiredStringValidator(fieldName="sex",errCode="ACM0205",errMsg="请求参数不足，性别不能为空"),
            @RequiredStringValidator(fieldName="acNo",errCode="ACM0207",errMsg="请求参数不足，学号不能为空"),
            @RequiredStringValidator(fieldName="cardId",errCode="ACM0208",errMsg="请求参数不足，身份证号不能为空")
    })
    @RequestMapping(value = "/add")
    public Callable<GenericResponse<String>> add(@RequestBody String json) {
        logger.info("***教师档案添加开始***入参：" + json);
        try {
            Teacher teacher = JsonUtil.jsonToObject(json,Teacher.class);
            if(ValidatorUtil.isEmail(teacher.getEmail())) {
                throw new Exception("邮箱格式不正确");
            }
            if (ValidatorUtil.isMobile(teacher.getPhone())) {
                throw new Exception("手机号格式不正确");
            }
            if (ValidatorUtil.isIDCard(teacher.getCardId())) {
                throw new Exception("身份证号不正确");
            }
            this.teacherService.add(teacher);
            logger.info("***教师档案添加成功***" + teacher);
            return () -> GenericResponse.success("ACM0008", "添加成功", teacher);
        } catch (Exception e) {
            logger.info("***教师档案添加失败***" + e);
            return () -> GenericResponse.failed("ACM0009", "添加失败" + e);
        }
    }

    @ApiOperation("查看详细教师档案")
    @RequestMapping(value = "/findOneById")
    public Callable<GenericResponse<String>> findOneById(@RequestBody String json) {
        logger.info("***教师档案查询开始***");
        try {
            Teacher teacher = JsonUtil.jsonToObject(json,Teacher.class);
            Teacher finalTeacher = this.teacherService.findOneById(teacher.getAcNo());
            logger.info("***教师档案查询成功***");
            return () -> GenericResponse.success("ACM0012", "详细查询成功", finalTeacher);
        } catch (Exception e) {
            return () -> GenericResponse.failed("ACM0013", "查询详情失败" + e);
        }
    }

    @RequiredStringValidator(fieldName="acNo",trim=true,errCode="ACM0207",errMsg="请求参数不足,学号不能为空空")
    @ApiOperation("更新教师信息")
    @RequestMapping(value = "/update")
    public Callable<GenericResponse<String>> update(@RequestBody String json, HttpSession session) {
        logger.info("***教师信息更新开始***入参：" + json);
        try {
            Teacher teacher = JsonUtil.jsonToObject(json,Teacher.class);
//            logger.info(session.getAttribute("login_user").toString());
//            if(!teacher.getAcNo().equals(session.getAttribute("login_user")) || !"2".equals(session.getAttribute("type"))) {
//                throw new Exception("对不起，您无操作权限");
//            }
            this.teacherService.updateById(teacher);
            logger.info("***教师信息更新成功***");
            return () -> GenericResponse.success("ACM0014", "更新成功", teacher);
        } catch (Exception e) {
            logger.error("***教师信息更新失败***" + e);
            return () -> GenericResponse.failed("ACM0015", "更新失败");
        }
    }

    @ApiOperation("查看全部教师档案，带分页")
    @RequestMapping(value = "/findAll")
    public Callable<GenericResponse<List<Teacher>>> findAll(@RequestBody String json, int pageNum, int pageSize) {
        logger.info("***查看全部教师档案（分页）***");
        try {
            Teacher teacher = JsonUtil.jsonToObject(json,Teacher.class);
            PageHelper.startPage(pageNum, pageSize);
            List<Teacher> list = this.teacherService.findAll(teacher);
            // 用PageInfo对结果进行包装
            PageInfo pageInfo = new PageInfo(list);
            logger.info("***查看全部教师档案（分页） 成功***" + pageInfo);
            return () -> GenericResponse.success("ACM0010", "查询成功", pageInfo);
        } catch (Exception e) {
            logger.info("***查看全部教师档案（分页）失败***" + e);
            return () -> GenericResponse.failed("ACM0011", "查询失败");
        }
    }
}